from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles  # 添加这行导入
from routers import users, goods, orders, chat
from config import settings
import uvicorn
import signal
import sys
import os

# 创建FastAPI应用实例
app = FastAPI(
    title="智能零售平台API",
    description="基于FastAPI和智谱AI的智能零售平台后端API",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 配置静态文件服务 - 添加这部分
app.mount("/static", StaticFiles(directory="static"), name="static")

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(users.router, prefix="/api/v1")
app.include_router(goods.router, prefix="/api/v1")
app.include_router(orders.router, prefix="/api/v1")
app.include_router(chat.router, prefix="/api/v1")


@app.get("/")
async def root():
    """根路径，返回API基本信息"""
    return {
        "message": "欢迎使用智能零售平台API",
        "version": "1.0.0",
        "docs": "/docs",
        "status": "running"
    }


@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {
        "status": "healthy",
        "service": "intelligent-retail-api",
        "timestamp": __import__('datetime').datetime.now().isoformat()
    }


@app.get("/api/v1/info")
async def api_info():
    """API基本信息"""
    return {
        "name": "智能零售平台API",
        "version": "1.0.0",
        "description": "基于FastAPI的智能零售平台后端服务",
        "endpoints": {
            "users": "/api/v1/users",
            "goods": "/api/v1/goods",
            "orders": "/api/v1/orders",
            "chat": "/api/v1/chat"
        }
    }


# 优雅关闭处理
def signal_handler(signum, frame):
    """信号处理函数"""
    print(f"\n📢 收到信号 {signum}，正在优雅关闭服务器...")
    sys.exit(0)


# 应用启动事件
@app.on_event("startup")
async def startup_event():
    """应用启动时执行"""
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    # 确保静态文件目录存在
    os.makedirs("static/avatars/default", exist_ok=True)

    print("🚀 智能零售平台API服务启动成功！")
    print(f"📍 本地访问: http://localhost:8000")
    print(f"📚 API文档: http://localhost:8000/docs")
    print(f"🔍 健康检查: http://localhost:8000/health")
    print(f"📁 静态文件: http://localhost:8000/static")
    print("⏹️  按 Ctrl+C 停止服务")


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时执行"""
    print("👋 智能零售平台API服务已关闭")


if __name__ == "__main__":
    try:
        # 开发环境直接运行
        uvicorn.run(
            "main:app",
            host="0.0.0.0",
            port=8000,
            reload=True,
            log_level="info"
        )
    except KeyboardInterrupt:
        print("\n👋 服务器已被用户中断")
    except Exception as e:
        print(f"❌ 服务器运行异常: {e}")